package myky.com.doctorapp.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.nukc.stateview.Constant;
import com.gyf.barlibrary.ImmersionBar;
import com.m7.imkfsdk.KfStartHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import myky.com.doctorapp.R;
import myky.com.doctorapp.adapter.MineFragmentAdapter;
import myky.com.doctorapp.api.Address;
import myky.com.doctorapp.entity.LocalUserEntity;
import myky.com.doctorapp.entity.MineFragmentEntity;


import myky.com.doctorapp.entity.UpUserInfoEvent;
import myky.com.doctorapp.entity.UserEntity;
import myky.com.doctorapp.base.BaseFragment;
import myky.com.doctorapp.base.CMApplication;

import myky.com.doctorapp.contract.MineFragmentContract;
import myky.com.doctorapp.entity.PageEntity;
import myky.com.doctorapp.presenter.MineFragmentPresenter;
import myky.com.doctorapp.ui.FollowDoctorListActivity;
import myky.com.doctorapp.ui.FeedBackActivity;
import myky.com.doctorapp.ui.HealthRecordHomePageActivity;
import myky.com.doctorapp.ui.HelpActivity;
import myky.com.doctorapp.ui.LoginActivity;
import myky.com.doctorapp.ui.MyConsultRecordActivity;
import myky.com.doctorapp.ui.MyDocotorActivity;
import myky.com.doctorapp.ui.PersonalInfo2Activity;
import myky.com.doctorapp.ui.SettingActivity;
import myky.com.doctorapp.utils.Constants;
import myky.com.doctorapp.utils.ShareUtil;
import myky.com.doctorapp.utils.SharedPre;
import myky.com.doctorapp.utils.UriUtils;

import static android.app.Activity.RESULT_OK;

/**
 * Description:
 *
 * @author wuyang
 * Created by 2018/12/28 10:46
 */
public class MineFragment extends BaseFragment<MineFragmentPresenter, UserEntity.PayLoadBean> implements MineFragmentContract.View, BaseQuickAdapter.OnItemChildClickListener {


    @BindView(R.id.header)
    SimpleDraweeView header;
    @BindView(R.id.sy_name)
    TextView syName;
    @BindView(R.id.sy_more)
    ImageView syMore;
    @BindView(R.id.login_layout)
    RelativeLayout loginLayout;
    @BindView(R.id.consult_mine)
    LinearLayout consultMine;
    @BindView(R.id.remote_mine)
    LinearLayout remoteMine;
    @BindView(R.id.appoint_mine)
    LinearLayout appointMine;
    @BindView(R.id.referral_mine)
    LinearLayout referralMine;
    @BindView(R.id.mine_fragment_recycler)
    RecyclerView mineFragmentRecycler;
    @BindView(R.id.mine_fragment_lin)
    LinearLayout mineFragmentLin;
    Unbinder unbinder;
    @BindView(R.id.login_lin)
    FrameLayout loginLin;
    private MineFragmentAdapter adapter;
    private List<MineFragmentEntity> dateList = new ArrayList<>();

    private final int PERSON_INTENT = 1;
    private final int LOGIN_INTENT = 2;
    private final int LOGOUT_INTENT = 3;
    private boolean loginOk;


    public MineFragment() {

    }

    public static MineFragment newInstance() {
        Bundle args = new Bundle();
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public MineFragmentPresenter getPresenter() {
        return new MineFragmentPresenter();
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).titleBar(loginLin).init();
        String[] stringArray = getActivity().getResources().getStringArray(R.array.mine_fragment_list);
        for (int i = 0; i < stringArray.length; i++) {
            MineFragmentEntity entity = new MineFragmentEntity(stringArray[i]);
            if (i == 3 || i == 7) {
                entity.setType(MineFragmentEntity.FOOTLAYOUT);
            } else {
                entity.setType(MineFragmentEntity.DEFAULT);
            }
            dateList.add(entity);
        }

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        mineFragmentRecycler.setLayoutManager(manager);
        adapter = new MineFragmentAdapter(dateList);
        mineFragmentRecycler.setAdapter(adapter);
        adapter.setOnItemChildClickListener(this);

        loginOk = CMApplication.getInstance().isLoginOk();

        setLoginStatus(loginOk);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {


    }




    private void getUserInfo() {

        mPresenter.getUserInfo();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected int injectTarget() {
        return R.id.mine_fragment_lin;
    }

    @Override
    protected void doRetry() {

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_mine;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.login_layout, R.id.consult_mine, R.id.remote_mine, R.id.appoint_mine, R.id.referral_mine})
    public void onViewClick(View view) {
        Intent intent = new Intent();

        switch (view.getId()) {

            case R.id.login_layout:
//                if (isLogin()) {
//                    intent.setClass(getActivity(), PersonalInfoActivity.class);
//                    startActivityForResult(intent, PERSON_INTENT);
//                }
                if (isLogin()) {
                    intent.setClass(getActivity(), PersonalInfo2Activity.class);
                    startActivityForResult(intent, PERSON_INTENT);
                }

                break;
            case R.id.consult_mine:
                if (isLogin()) {
                    intent.setClass(getActivity(), MyConsultRecordActivity.class);
                    startActivity(intent);
                }
                break;
//            case R.id.remote_mine:
//
//
//                break;
//            case R.id.appoint_mine:
//                if (isLogin()) {
//                    intent.setClass(getActivity(), Bespeak_ListActivity.class);
//                    startActivity(intent);
//                }
//                break;
//            case R.id.referral_mine:
//                if (isLogin()) {
//                    intent.setClass(getActivity(), TransferListActivity.class);
//                    startActivity(intent);
//                }
//
//                break;
            default:

                break;
        }


    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

//        MineFragmentEntity entity = (MineFragmentEntity) adapter.getData().get(position);
//        Intent intent=new Intent();
        switch (position) {
            case 0:
                if (isLogin()) {
                    startActivity(FollowDoctorListActivity.class);
                }
                break;
//            case 1:
//                if (isLogin()){
//                    intent.setClass(getActivity(),New_CaseActivity.class);
//                    startActivity(intent);
//                }
//                break;
            case 2:
                if (isLogin()){

                    startActivity(HealthRecordHomePageActivity.class);
                }
                break;
            case 3:
                if (isLogin()){

                    Intent intent=new Intent();

                    intent.setClass(getActivity(), MyDocotorActivity.class);
                    startActivity(intent);
                }
                break;
            case 4:
//
            LocalUserEntity user_bean = SharedPre.getUser_bean(getActivity());

            String username,userId,mobile,nickName;


            if (user_bean != null && user_bean.getUserName() != null && !TextUtils.isEmpty(user_bean.getUserName())) {
                username = SharedPre.getUser_bean(getActivity()).getUserName();
            } else {
                username = "访客";
            }
            if (user_bean != null && user_bean.getPhone() != null && !TextUtils.isEmpty(user_bean.getPhone())) {
                mobile = SharedPre.getUser_bean(getActivity()).getPhone();
            } else {
                mobile = "";
            }


            if (CMApplication.getInstance().isLoginOk()) {
                userId = ShareUtil.getUserId(Constants.USERID);
                nickName = username + "_" + mobile;
            } else {
                userId = String.valueOf(((Math.random() * 9 + 1) * 1000));
                nickName = "访客";
            }


            KfStartHelper helper =new KfStartHelper(getActivity());
            helper.initSdkChat("ba6bf790-4f86-11e8-a899-6d1f9ec76555", nickName, userId);

            break;
            case 5:

                startActivity(HelpActivity.class);
                break;
            case 6:

                startActivity(FeedBackActivity.class);

                break;
            case 7:
                startActivityForResult(SettingActivity.class, LOGOUT_INTENT);

                break;

            default:
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i("out", "LOGIN_INTENT...........data" + requestCode + resultCode + data);
        if (data != null && resultCode == RESULT_OK) {

            switch (requestCode) {
                case PERSON_INTENT:
                    getUserInfo();
                    break;
                case LOGIN_INTENT:
                    if (data.hasExtra("IS_LOGIN")) {
                        setLoginStatus(true);
                    } else {
                        setLoginStatus(false);
                    }
                    break;
                case LOGOUT_INTENT:
                    if (data.hasExtra("IS_LOGOUT")) {
                        setLoginStatus(false);
                    }
                    break;
                default:
                    break;
            }
        }
    }


    private void setLoginStatus(boolean islogin) {

        if (islogin) {

            ShareUtil.putData(Constants.ISLOGIN, true);
            syMore.setVisibility(View.VISIBLE);
            getUserInfo();
        } else {
            ShareUtil.putData(Constants.ISLOGIN, false);
            header.setImageURI(UriUtils.getUriInstance().getUri(Constant.LOCALRESOURCE, R.mipmap.icon2));
            syMore.setVisibility(View.GONE);
            syName.setText("登录/注册");
        }

    }

    private boolean isLogin() {

        boolean loginOks = CMApplication.getInstance().isLoginOk();
        if (loginOks) {
            return true;
        } else {
            startActivityForResult(LoginActivity.class, LOGIN_INTENT);
        }

        return false;
    }

    @Override
    public void showDataError(String errorMessage) {

    }

    @Override
    public void showDataSuccess(UserEntity.PayLoadBean datas) {

    }

    @Override
    public void showPages(PageEntity pageEntity) {

    }


    @Override
    public void showUserInfo(UserEntity.PayLoadBean userBean) {

        header.setImageURI(UriUtils.getUriInstance().getUri(Constant.ONLINEPIC, Address.IMAGE + userBean.getHeadPhoto()));
        syMore.setVisibility(View.VISIBLE);
        String username = userBean.getRealname();
        if (!TextUtils.isEmpty(userBean.getNickname())) {
            username = userBean.getNickname();
        }
        syName.setText(username);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
   public void scrollToFirst(UpUserInfoEvent upUserInfoEvent) {

        String userAdvanter = upUserInfoEvent.getUserAdvanter();
        String userName = upUserInfoEvent.getUserName();

        if(userAdvanter!=null){
            header.setImageURI(Address.IMAGE+userAdvanter);

        }if(userName!=null){
            syName.setText(userName);

        }

    }
}
